package com.et.machine.manager.vm.internet

import androidx.lifecycle.ViewModel
import com.et.machine.manager.vm.internet.InternetFragment.Companion.A_LI_YUN
import com.et.machine.manager.vm.internet.InternetFragment.Companion.BAI_DU
import com.et.machine.manager.vm.internet.InternetFragment.Companion.QQ
import com.et.machine.util.okHttpClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import java.io.IOException
import java.net.SocketTimeoutException
import java.text.SimpleDateFormat
import java.util.*

data class Result(
    var time: Int = 0,
    var content: String = "unsuccessful"
)

class InternetViewModel : ViewModel() {
    suspend fun getWorkStatus(url: String): Result = withContext(Dispatchers.IO) {
        val urlName = when (url) {
            BAI_DU -> "百度"
            QQ -> "腾讯"
            A_LI_YUN -> "阿里云"
            else -> url
        }
        return@withContext Result().apply {
            try {
                val start = System.currentTimeMillis()
                okHttpClient.newCall(Request.Builder().url(url).get().build()).execute().apply {
                    val currentTimeMillis = System.currentTimeMillis()
                    time = (currentTimeMillis - start).toInt()
                    val date = SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.getDefault()).format(
                        Date(currentTimeMillis)
                    )
                    content = "<font color=\"#26AAAA\">$date: $urlName - 请求成功！</font>"
                }
            } catch (e: SocketTimeoutException) {
                val date = SimpleDateFormat(
                    "yyyy年MM月dd日 HH:mm:ss",
                    Locale.getDefault()
                ).format(Date(System.currentTimeMillis()))
                content = "<font color=\"#333333\">$date: $urlName - 连接超时，请检查网络连接！</font>"
            } catch (e: IOException) {
                val date = SimpleDateFormat(
                    "yyyy年MM月dd日 HH:mm:ss",
                    Locale.getDefault()
                ).format(Date(System.currentTimeMillis()))
                content = "<font color=\"#E23737\">$date: $urlName - 请求失败，请检查网络连接！</font>"
            }
        }
    }

}